package com.bingo.generate.cli.Cmds;


import com.bingo.generate.comm.entity.ColInfo;
import com.bingo.generate.comm.entity.TableInfo;
import com.bingo.generate.comm.service.GenerateDbService;
import com.bingo.generate.comm.util.FmUtil;
import com.bingo.generate.comm.util.JdbcUtil;
import com.bingo.generate.comm.util.bean.SqlBeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName    生成sql脚本的命令
 * Description
 * Create by lc
 * Date 2021/7/19 13:37
 */
public class SqlCodeCmd {

    //  返回两张表有数据差异的列
    public static Map<String, List<ColInfo>> compare(String key1, String key2) {
        //  第一张表的列对象
        List<ColInfo> list1 = GenerateDbService.ins.searchCols(key1);
        //  第二张表的列对象
        List<ColInfo> list2 = GenerateDbService.ins.searchCols(key2);
        List<ColInfo> allList = new ArrayList();
        allList.addAll(list1);
        allList.addAll(list2);
        //  根据列名进行分组
        Map<String, List<ColInfo>> listMap = allList.stream().collect(Collectors.groupingBy(ColInfo::getColName));
        return listMap;
    }

    public static void createAddFtl(String tbName, List<ColInfo> list) {
        Map map = new HashMap();
        map.put("cols", list);
        map.put("tbName", tbName);
        FmUtil.print("sqlTipsAdd.ftl", map);
    }

    public static String getDefaultSql(ColInfo col) {
        if (col.getDefaultVal() == null) {
            return "";
        }
        switch (col.getType()) {
            case "varchar":
                return String.format("DEFAULT '%s'", col.getDefaultVal());
            case "tinyint":
            case "int":
                return String.format("DEFAULT %s", col.getDefaultVal());
            default:
                throw new RuntimeException("还未配置该类型的默认值形式 " + col.getType());
        }
    }

    public static void idToLang(List<ColInfo> colList) {
        for (ColInfo colInfo : colList) {
            String nullStr = "NOT NULL";
            if (colInfo.isCanNull()) {
                nullStr = "NULL";
            }
            String str = String.format("ALTER TABLE `%s` \n" +
                    "MODIFY COLUMN `%s` bigint(20) UNSIGNED %s COMMENT '%s';", colInfo.getTableName(), colInfo.getColName(), nullStr, colInfo.getComment());
            System.out.println(str);
        }
    }

    public static boolean isLongId(List<ColInfo> colList, List<ColInfo> outList) {
        for (ColInfo colInfo : colList) {
            //  找到id字段
            if (colInfo.getColName().toLowerCase().indexOf("id") != -1) {
                if (colInfo.getType().toLowerCase().equals("string")) {
                    continue;
                }
                if (colInfo.getType().toLowerCase().equals("int")) {
                    //System.out.println("id为int的id字段 "+colInfo.getTableName()+"."+colInfo.getColName());
                    outList.add(colInfo);
                    continue;
                }
            }
        }
        return true;
    }

    public static String getAddIdFk(String dbName, List<TableInfo> tableNameList) {
        StringBuilder strBud = new StringBuilder();
        for (TableInfo tableInfo : tableNameList) {
            String sql = "SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE,COLUMN_KEY,COLUMN_COMMENT FROM information_schema.`COLUMNS`  WHERE TABLE_NAME ='" + tableInfo.getTableName() + "' and TABLE_SCHEMA='" + dbName + "' ";
            List<Map<String, Object>> listMap = JdbcUtil.ins.queryForList(sql);
            String res = "";
            for (Map<String, Object> map : listMap) {
                ColInfo colInfo = SqlBeanUtil.mapToBean(map, ColInfo.class);
                //  如果没有id字段
                if (!colInfo.getColName().toLowerCase().endsWith("id")) {
                    continue;
                }
                if (StringUtils.isNotEmpty(colInfo.getColumnKey())) {
                    continue;
                }
                /*System.out.println(String.format("检测到字段没有加索引 表:%s \t\t\t字段:%s",colInfo.getTableName(),colInfo.getColName()));*/
                String str = String.format("create index `%s_foreign_index` on %s (%s);", colInfo.getColName(), colInfo.getTableName(), colInfo.getColName());
//                strBud.append(str).append("\n");
                res += (str + "\n");
            }
            if (res.length() > 0) {
                strBud.append("-- " + tableInfo.getTableName()).append("\t\t").append(tableInfo.getTableComment()).append("\n");
                strBud.append(res);
                strBud.append("\n");
            }
        }
        System.out.println(strBud);
        return strBud.toString();
    }

    /**
     * 找到了不是long的表的字段
     */
    public static List<ColInfo> getTbNoLong(String dbName) {
        List<ColInfo> outList = new ArrayList<>();
        List<TableInfo> tbList = GenerateDbService.ins.searchTable(dbName);
        for (TableInfo tableInfo : tbList) {
            //  判断是否id为Long类型
            List<ColInfo> colInfos = GenerateDbService.ins.searchCols(dbName, tableInfo.getTableName());
            boolean isOk = isLongId(colInfos, outList);
            /*if(!isOk){
                continue;
            }*/
            //System.out.println(tableInfo.getTableName());
        }
        return outList;
    }

}
